package com.sz.pc.controller.user;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.plugins.Page;
import com.feilong.core.Validator;
import com.feilong.core.bean.ConvertUtil;
import com.sz.pc.controller.base.BaseController;
import com.sz.pc.entity.model.Pager;
import com.sz.pc.entity.model.ResultDataEnum;
import com.sz.pc.entity.model.ResultModel;
import com.sz.pc.entity.tb.TbRole;
import com.sz.pc.entity.tb.TbUser;
import com.sz.pc.service.interfs.user.ITbRoleService;
import com.sz.pc.service.interfs.user.ITbUserService;
import com.sz.pc.utils.EndecryptUtils;
import com.sz.pc.utils.JsonUtil;

/**
 * <p>
 * 用户账户表  前端控制器
 * </p>
 *
 * @author xj
 * @since 2016-12-20
 */
@Controller
@RequestMapping("/user/")
public class TbUserController extends BaseController{
	@Autowired
	private ITbUserService userService;
	@Autowired
	private ITbRoleService roleService;
	
	@GetMapping("listUI")
    public String listUI() {
		return "user/list";
    }
	
	@PostMapping("list")
	@ResponseBody
    public Object list(String gridPager) {
		Pager pager = JsonUtil.getObjectFromJson(gridPager, Pager.class);
		Map<String, Object> parameters = null;
		String name = "";
		if(Validator.isNullOrEmpty(pager.getParameters())){
			parameters = new HashMap<>();
		}else{
			parameters = pager.getParameters();
			name = parameters.get("name").toString();
		}
		Page<TbUser> list = userService.selectUserList(new Page<TbUser>(pager.getNowPage(), pager.getPageSize()),name);
		parameters.clear();
		parameters.put("isSuccess", Boolean.TRUE);
		parameters.put("nowPage", pager.getNowPage());
		parameters.put("pageSize",pager.getPageSize());
		parameters.put("pageCount", list.getPages());
		parameters.put("recordCount", list.getTotal());
		parameters.put("startRecord", list.getOffsetCurrent());
		parameters.put("exhibitDatas",list.getRecords());
		return parameters;
    }
	
	@GetMapping("form")
    public String form(Map<String,Object> map) {
		List<TbRole> list = roleService.selectByMap(null);
		map.put("roles", list);
		return "user/form";
    }
	
	@GetMapping("checkAccount")
	@ResponseBody
    public boolean checkAccount(@RequestParam(required=true) String accountName) {
		List<TbUser> user = userService.selectByMap(ConvertUtil.toMap("u_account_name",(Object)accountName));
		if(!Validator.isNullOrEmpty(user)){
			return false;
		}
		return true;
    }
	
	@PostMapping("save")
	@ResponseBody
	public Object add(Map<String,Object> map,TbUser user){
		if(user.getId()==null){
			// 加密用户输入的密码，得到密码和加密盐，保存到数据库
			TbUser userEntity = EndecryptUtils.md5Password(user.getAccountName(), user.getPassword(), 2);
			//设置添加用户的密码和加密盐
			user.setPassword(userEntity.getPassword());
			user.setCredentialsSalt(userEntity.getCredentialsSalt());
			//设置创建者姓名
			user.setCreatorName("test");
			user.setCreateTime(new Date(System.currentTimeMillis()));
			user.setUpdateTime(new Date(System.currentTimeMillis()));
			//设置锁定状态：未锁定；删除状态：未删除
			user.setLocked(0);
			user.setDeleteStatus(0);
			boolean result = userService.insertAll(user);
			if(!result)
			{
				return success(ResultDataEnum.PARAMS_ERROR);
			}
		}else{
			userService.updateAll(user);
		}
		return success();
	}
	
	@DeleteMapping("{userId}/delete")
	@ResponseBody
    public ResultModel delete(@PathVariable(required=true) Integer userId) {	
		if(!userService.delUser(userId)){
			return success(ResultDataEnum.PARAMS_ERROR);
		}
		return success();
    }	
	
	@GetMapping("{userId}/select")
    public String select(Map<String,Object> map,@PathVariable(required=true) Integer userId) {	
		TbUser user = userService.selectUserRole(ConvertUtil.toMap("userId",(Object)userId));
		List<TbRole> list = roleService.selectByMap(null);
		map.put("roles", list);
		map.put("user", user==null?new TbUser():user);
		return "user/edit";
    }	
	
	@GetMapping("{userId}/toRestPassword")
    public String restPassword(Map<String,Object> map,@PathVariable(required=true) Integer userId) {	
		TbUser user = userService.selectById(userId);
		map.put("user", user);
		return "user/rest";
    }
	
	@GetMapping("userToRestPassword")
	public String userToRestPassword(Map<String,Object> map){
		TbUser userInfo = (TbUser)SecurityUtils.getSubject().getSession().getAttribute("userSession");
		map.put("user", userInfo);
		return "user/rest";
	}
	
	@PostMapping(value = "restPassword")
	@ResponseBody
	public ResultModel restPassword(Map<String,Object> map,TbUser user,String isSelf,String oldPassword){
		if("true".equals(isSelf)){//自己修改，需要输入旧密码
			String msg = "";
			UsernamePasswordToken token = new UsernamePasswordToken(user.getAccountName(), oldPassword);
			token.setRememberMe(false);
	        Subject subject = SecurityUtils.getSubject();
	        subject.getSession().setAttribute("account", user.getAccountName());
	        try{
	        	subject.login(token);
	        	subject.getSession().removeAttribute("msg");
	        }catch(UnknownAccountException e){
				msg = "账户不存在！";
	        }catch(IncorrectCredentialsException e){
				msg = "原密码错误！";
	        }catch (LockedAccountException e) {
	        	msg = "您的账户已被锁定,请与管理员联系！";
	        }catch(ExcessiveAttemptsException e){
	        	msg = "登录失败次数过多,请稍后再试！";
	        }catch(Exception e){
	        	 msg="系统发生错误，请联系管理员！";
	        }
	        if(msg.length()>0){
	        	return success(ResultDataEnum.OLD_PWD_ERROR.getCode(),msg,"");
	        }
		}
		
		
		TbUser userEntity = userService.selectById(user.getId());
		TbUser userFlag = EndecryptUtils.md5Password(user.getAccountName(), user.getPassword(), 2);
		//设置添加用户的密码和加密盐
		userEntity.setPassword(userFlag.getPassword());
		userEntity.setCredentialsSalt(userFlag.getCredentialsSalt());
		userEntity.setUpdateTime(new Date(System.currentTimeMillis()));
		if(!userService.updateById(userEntity)){
			return success(ResultDataEnum.PARAMS_ERROR);
		}
		return success();
	}
}
